$NG.AllReady(function (page, { useAction, useValuesChange, useImpPullData, useDataIndexChange, useUpdateRow, useUpdateRows }) {
    console.log("page is ready");
    console.log("page", page, page.isList);
    console.log($NG.getPageUI());
    console.log($NG.getPageState());
    let config = {
        new_suppy: 0, // 记录明细供应商是否发生变化
        old_suppy: null
    }
    if(page.oType != 'view'){
        sumAmt()
    }
    const mstfrom = $NG.getCmpApi("PaymentBill_Form")
    const dgrid = $NG.getCmpApi("grid_PaymentBillD");
    console.log(dgrid);
    const toolbar = $NG.getCmpApi("toolbar");
    const user = $NG.getUser()
    if (page.isList) {
        setTimeout(() => {
            try {
                const toolbar = $NG.getCmpApi("toolbar")
                const buttons = toolbar.getButtons()
                buttons.forEach(item => {
                    if (item.id == 'add') {
                        let ins = null
                        item.children.forEach((el, index) => {
                            if (el.text == '付供应商款') {
                                ins = el
                            }
                        })
                        item.children = [ins]
                    }
                })
                // 使用隐藏间接触发刷新
                toolbar.getItem("add").setHidden(false)
            } catch (err) {
                console.error('隐藏部分新增方案失败，不影响下面代码执行', err)
            }
        }, 300)
    }
    console.log(`ceshi page`, page, page.oType);
    if (!mstfrom.getItem("PhidApplyPsn").getValue()) {
        mstfrom.getItem("PhidApplyPsn").setValue({
            label: user.userName,
            value: user.userID
        })
        $NG.execServer("GETuserdept", { phid: $NG.getUser().userID }, (res) => {
            console.log(res)
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            mstfrom.getItem("PhidDept").setValue({
                label: _data.deptname,
                value: _data.dept_id
            })
        })
    }
    // init()
    // function init(){
    //     mstfrom.getItem("Remark").setValue("无")
    // }

    if (!mstfrom.getItem("Remark").getValue()) {
        mstfrom.getItem("Remark").setValue('无')
    }

    // toolbar.getItem("billQuote").setHidden();
    isDate()
    function isDate() {
        setTimeout(() => {
            if (!mstfrom.getItem("user_plan_dt").getValue() && mstfrom.getItem("PhidPayway").getValue() == 8570000000000001) {
                console.log(`xian hui`);
                const date = new Date()
                mstfrom.getItem("user_plan_dt").setValue(`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`)
            }
        }, 500)
    }
    // 监听 PhidPayway
    useValuesChange(({ args }) => {
        console.log(`监听结算方式`);
        console.log(args);

        let isXianHui = false;

        if (mstfrom.getItem("PhidPayway").getValue() == 8570000000000001) {
            console.log(`xian hui`);
            const date = new Date()
            mstfrom.getItem("user_plan_dt").setValue(`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`)
            isXianHui = true;
        }
        const fields = ["user_pj_pay", "user_pjqx"];

        $NG.updateUI((updater) => {
            console.log(updater);
            updater.fieldSetForm.PaymentBill.user_pay_qd.setProps({
                required: isXianHui, //必输
            });
            fields.forEach((field) => {
                updater.fieldSetForm.PaymentBill[field].setProps({
                    required: !isXianHui, //必输
                });
            });
        });
    }, "fc3_payment_bill.PhidPayway");

    useValuesChange(({ args }) => {
        hideKey()
        console.log(`监听业务类型`, args);
    }, "fc3_payment_bill.PhidBusType")

    /* 明细 */
    useUpdateRows(({ args }) => {
        sumAmt(args[0])
        console.log(`useUpdateRows`,"被触发");
    }, "grid_PaymentBillD");

    function sumAmt(datas){
        const mstfrom = $NG.getCmpApi("PaymentBill_Form")
        const dgrid = $NG.getCmpApi("grid_PaymentBillD");
        let rows = null
        if(datas){
            rows = datas
        } else {
            rows = dgrid.getRows()
        }
        
        console.log(rows);
        let name1 = rows[0].PhidCon_EXName;
        let name3 = rows[0].user_yght_no_name;
        let name2 = mstfrom.getItem("PhidBusType").getText()
        if (mstfrom.getItem("PhidBusType").getValue() == 51) {
            mstfrom.getItem("BillName").setValue(`${name3}-${name2}`)
        } else {
            mstfrom.getItem("BillName").setValue(`${name1}-${name2}`)
        }
        // rows.forEach((items) => {
        //     config.new_suppy = items.PhidSupplyEnt_EXName
        //     $NG.execServer("getSuppyInfo", { phid: items.PhidSupplyEnt }, function (res) {
        //         console.log("getSuppyInfo", res);
        //         try {
        //             const datas = JSON.parse(res.data)[0].extendObjects;
        //             console.log(datas);
        //             items.RecAccNo = datas.user_yhzh;
        //             items.RecAccName = datas.user_yhzhmc;
        //             items.PhidBank = datas.user_bank_name;
        //             items.PhidBank_EXName = datas.bphid;
        //             dgrid.refreshView();
        //             //   instance.updateRow(args[0]);
        //         } catch (error) {
        //             console.error("解析银行信息失败：", error);
        //         }
        //     });
            // if (!items.PhidFcur) {
            //     items.PhidFcur = 1;
            //     items.PhidFcur_EXName = '人民币'
            // }
        // });
        if (config.new_suppy != config.old_suppy) {
            config.old_suppy = config.new_suppy
            getSuppyInNbgys()
        }
        dgrid.refreshView();
    }
    useDataIndexChange(({ args, instance }) => {
        console.log(`监听 fc3_payment_bill_d PhidSupplyEnt`, args);
        const record = args[0];
        console.log(record.PhidSupplyEnt);

        $NG.execServer("searchGys", { phid: record.PhidSupplyEnt }, function (res) {
            console.log("searchGys", res);
            try {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(datas);
                record.RecAccNo = datas.user_yhzh;
                record.RecAccName = datas.user_yhzhmc;
                record.PhidBank = datas.taxbank_id;
                record.PhidBank_EXName = datas.taxbankname;
                instance.updateRow(args[0]);
            } catch (error) {
                console.error("解析银行信息失败：", error);
            }
        });
    }, "fc3_payment_bill_d.PhidSupplyEnt");
    useDataIndexChange(({ args, instance }) => {
        console.log(`外包合同触发监听`, args);
        const map = args[1].update.originValue
        args[0].user_htlx = map.htlx
        args[0].user_wbyght_no = map.bill_no
        instance.updateRow(args[0])
    }, "fc3_payment_bill_d.user_yght_no");
    filterM()
    function filterM() {
        $NG.updateUI((updater, state) => {
            console.log(`过滤参数检查`, updater);
            updater.fieldSetForm.PaymentBill.PhidBusType.setProps({
                clientSqlFilter: `phid in (19,20,51)`
            });
        });
    }

    // 获取供应商是否是内部供应商
    function getSuppyInNbgys() {
        $NG.execServer("getSuppyInNbgys", { gys: config.new_suppy }, (res) => {
            if (res.count == 0) {
                mstfrom.getItem("user_sfwnbdw").setValue("0")
                return
            }
            mstfrom.getItem("user_sfwnbdw").setValue("1")
        })
    }

    // 业务类型发生变化隐藏字段
    hideKey()
    function hideKey() {
        const PhidBusType = mstfrom.getItem("PhidBusType").getValue()
        let lock = false
        let bool = false
        let bool2 = false
        switch (PhidBusType) {
            case 51:
                bool = true
                bool2 = false
                lock = true
                break
            case 19:
            case 20:
                bool2 = true
                bool = false
                lock = true
                break
            default:
                lock = false
                bool = false
                bool2 = false
        }
        $NG.updateUI((updater, state) => {
            console.log(`过滤参数检查`, updater);
            updater.grid.PaymentBillD.PhidCon.setProps({
                hidden: bool,
                required: !lock ? false : !bool
            });
            updater.grid.PaymentBillD.PhidCon_EXName.setProps({
                hidden: bool,
                required: !lock ? false : !bool
            });
            updater.grid.PaymentBillD.user_wbyght_no.setProps({
                hidden: bool2,
                required: !lock ? false : !bool2
            });
            updater.grid.PaymentBillD.user_yght_no.setProps({
                hidden: bool2,
                required: !lock ? false : !bool2
            });
        });
    }
});
